package com.labofjet.system.service.impl;

import com.github.pagehelper.PageInfo;
import com.labofjet.common.dto.ContextDto;
import com.labofjet.common.util.JSONUtils;
import com.labofjet.system.annotation.RedisCacheEvicat;
import com.labofjet.system.constant.CRedisCacheConstant;
import com.labofjet.system.dto.SysDictionaryDto;
import com.labofjet.system.dto.SysDictionaryExample;
import com.labofjet.system.mapper.SysDictionaryMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * serviceImpl类
 */
@Service
public class SysDictionaryServiceImpl extends CrudBaseServiceImpl<SysDictionaryDto> {
	@Resource
	private SysDictionaryMapper sysDictionaryMapper;

	public List<SysDictionaryDto> listPage(ContextDto result) {
		Map<String, Object> map = super.prepare(result);
		List<SysDictionaryDto> sysDictionaryDtos = sysDictionaryMapper.selectList(map);
		return sysDictionaryDtos;
	}

	@Override
	@Cacheable(value = CRedisCacheConstant.DIC_PAGE_PREFIX, key = CRedisCacheConstant.CACHE_PAGE)
	public PageInfo<SysDictionaryDto> list(ContextDto result) {
		Map<String, Object> map = super.prepare(result);
		List<SysDictionaryDto> SysDictionaryDtos = sysDictionaryMapper.selectList(map);
		return new PageInfo<>(SysDictionaryDtos);
	}

	@Override
	@Cacheable(value = CRedisCacheConstant.DIC_ID_PREFIX, key = CRedisCacheConstant.CACHE_ID)
	public SysDictionaryDto load(ContextDto result) {
		Map<String, Object> map = super.getRequestParamsMap(result);
		Integer id = (Integer) map.get("id");
		if (null != id) {
			return sysDictionaryMapper.selectList(map).get(0);
		}
		return null;
	}

	@Override
	@Transactional
	@Caching(evict = {
			@CacheEvict(value = CRedisCacheConstant.DIC_ID_PREFIX, key = CRedisCacheConstant.CACHE_EVICT_ID)
	})
	@RedisCacheEvicat(evict = @CacheEvict(value = CRedisCacheConstant.DIC_PAGE_PREFIX, allEntries = true))
	public SysDictionaryDto save(ContextDto result) {
		SysDictionaryDto dto = JSONUtils.getRequestData(result, SysDictionaryDto.class);
		if (dto.getId() != null) {
			sysDictionaryMapper.updateByPrimaryKey(dto);
		} else {
			sysDictionaryMapper.insertSelective(dto);
		}
		return dto;
	}

	@Override
	@Transactional
	@RedisCacheEvicat(evict = {@CacheEvict(value = CRedisCacheConstant.DIC_PAGE_PREFIX, allEntries = true),
		@CacheEvict(value = CRedisCacheConstant.DIC_ID_PREFIX)})
	public int delete(ContextDto result) {
		List<Integer> ids = JSONUtils.getRequestData(result, List.class);
		SysDictionaryExample example = new SysDictionaryExample();
		example.createCriteria().andIdIn(ids);
		int i = sysDictionaryMapper.deleteByExample(example);
		return i;
	}
}
